package com.chookss.home.document;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.home.adapter.DocunmentListAdapter;
import com.chookss.home.entity.DocunmentEntity;
import com.chookss.tools.AESEncrypt;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.DocunmentTypeDialog;
import com.chookss.view.RecycleViewDivider;
import com.chookss.view.listener.ShareChoiceDialogListener;
import com.google.gson.reflect.TypeToken;
import com.liulishuo.okdownload.DownloadTask;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.annotations.NonNull;

public class DocumentBaseSecondActivity extends BaseAct {

    public Context mContext;
    @BindView(R.id.iv_DataBaseBack)
    ImageView iv_DataBaseBack;
    @BindView(R.id.tvDatabaseSecondTitle)
    TextView tvDatabaseSecondTitle;
    @BindView(R.id.srlView)
    SmartRefreshLayout srlView;
    @BindView(R.id.rvView)
    RecyclerView rv;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.lvDiretory)
    RecyclerView lvDiretory;
    @BindView(R.id.rlvDiretory)
    RelativeLayout rlvDiretory;
    @BindView(R.id.ivTitleArrow)
    ImageView ivTitleArrow;
    @BindView(R.id.llSort)
    LinearLayout llSort;
    @BindView(R.id.tvSort)
    TextView tvSort;
    private DocunmentListAdapter adapter;
    private List<DocunmentEntity> list = new ArrayList<>();
    private ArrayList<Map<String, String>> directoryList = new ArrayList<>();
    private ArrayList<Map<String, String>> highDirectoryList = new ArrayList<>();
    private int currentPage = 1;
    private String pageSize = "20";
    private boolean isEnd = false;//是否到底
    private String parantCode;
    private int index = 0;//默认选择目录下标
    private int level = 1;//默认层级
    private List<Map<String, String>> dialogList = new ArrayList<>();
    private DocunmentTypeDialog bottomListsDialog = null;
    private int orderType = 0;//0--时间 1--名称 2--类别 3--大小
    private String orderMode = "desc";//升序 asc 降序 desc

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_document_base_second);
        mContext = this;
        initState();
        //接收参数
        Bundle bundle = getIntent().getExtras();
        ArrayList list = bundle.getParcelableArrayList("list");
        //从List中将参数转回 List<Map<String, Object>>
        highDirectoryList = (ArrayList<Map<String, String>>) list.get(0);
        parantCode = bundle.getString("parantCode");
        level = getIntent().getIntExtra("level", 1);
        String titleName = bundle.getString("title");
        tvDatabaseSecondTitle.setText(titleName);
        for (int i = 0; i < highDirectoryList.size(); i++) {
            if (highDirectoryList.get(i).get("title").equals(titleName)) {
                index = i;
            }
        }
        registerBoradcastReceiver();
    }

    @Override
    public void initData() {
        llSort.setOnClickListener(v -> {
            if (bottomListsDialog != null) {
                bottomListsDialog.show();
            }
        });
        Map<String, String> map = new HashMap<>();
        map.put("name", "时间排序");
        map.put("type", "1");
        dialogList.add(map);
        Map<String, String> map2 = new HashMap<>();
        map2.put("name", "名称排序");
        map2.put("type", "1");
        dialogList.add(map2);
        Map<String, String> map3 = new HashMap<>();
        map3.put("name", "文件大小排序");
        map3.put("type", "1");
        dialogList.add(map3);
        bottomListsDialog = new DocunmentTypeDialog(mContext, dialogList, new ShareChoiceDialogListener() {
            @Override
            public void onClick(int position) {
                tvSort.setText(dialogList.get(position / 2).get("name"));
                if (position == 0) {
                    orderType = 0;
                    orderMode = "asc";
                } else if (position == 1) {
                    orderType = 0;
                    orderMode = "desc";
                } else if (position == 2) {
                    orderType = 1;
                    orderMode = "asc";
                } else if (position == 3) {
                    orderType = 1;
                    orderMode = "desc";
                } else if (position == 4) {
                    orderType = 3;
                    orderMode = "asc";
                } else if (position == 5) {
                    orderType = 3;
                    orderMode = "desc";
                }
                currentPage = 1;
                isEnd = false;
                getData();
            }
        });
        if (highDirectoryList.size() > 1) {
            initLvDiretory();
            ivTitleArrow.setVisibility(View.VISIBLE);
        }
        iv_DataBaseBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tvDatabaseSecondTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (highDirectoryList.size() > 1) {
                    rlvDiretory.setVisibility(View.VISIBLE);
                    ivTitleArrow.setBackgroundResource(R.mipmap.icon_up_blacks);
                }
            }
        });
        ivTitleArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (highDirectoryList.size() > 1) {
                    rlvDiretory.setVisibility(View.VISIBLE);
                    ivTitleArrow.setBackgroundResource(R.mipmap.icon_up_blacks);
                }
            }
        });
        rv.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        adapter = new DocunmentListAdapter(R.layout.item_database_list, this, list, level, 0, directoryList, "DocumentBaseSecondActivity_DownloadFile" + level);
        rv.setAdapter(adapter);
        srlView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        srlView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                currentPage = 1;
                getData();
            }
        });
        srlView.autoRefresh();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize);
        map.put("parantCode", parantCode);
        map.put("orderType", orderType + "");
        if (!Utils.isNull(orderMode)) {
            map.put("orderMode", orderMode);
        }
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<DocunmentEntity>>>() {
        }.getType(), null, Urls.getByCode, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<DocunmentEntity>>() {
            @Override
            public void onSuccess(List<DocunmentEntity> data) {
                loadEnd();
                if (currentPage == 1) {
                    list.clear();
                    directoryList.clear();
                    adapter.notifyDataSetChanged();
                }
                if (srlView == null || llNone == null) {
                    return;
                }
                if (data != null && data.size() > 0) {
                    for (int i = 0; i < data.size(); i++) {
                        if ("0".equals(data.get(i).getDataType())) {
                            Map<String, String> map = new HashMap<>();
                            map.put("title", data.get(i).getDataTitle());
                            map.put("dataCode", data.get(i).getDataCode());
                            directoryList.add(map);
                        }
                    }
                    list.addAll(data);
                    adapter.notifyDataSetChanged();
                    srlView.setVisibility(View.VISIBLE);
                    llNone.setVisibility(View.GONE);
                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        srlView.setVisibility(View.GONE);
                        llNone.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void loadEnd() {
        if (null != srlView && srlView.getState() == RefreshState.Refreshing)
            srlView.finishRefresh();
        if (null != srlView && srlView.getState() == RefreshState.Loading)
            srlView.finishLoadMore();
    }

    private void initLvDiretory() {

        lvDiretory.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        lvDiretory.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, Utils.dip2px(this, 0.5f), getResources().getColor(R.color.line_gray)
        ));
        DirectorysAdapter adapter = new DirectorysAdapter(R.layout.item_diretory, mContext, highDirectoryList);
        lvDiretory.setAdapter(adapter);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@androidx.annotation.NonNull BaseQuickAdapter<?, ?> adapter, @androidx.annotation.NonNull View view, int position) {
                tvDatabaseSecondTitle.setText(highDirectoryList.get(position).get("title"));
                parantCode = highDirectoryList.get(position).get("dataCode");
                srlView.autoRefresh();
                index = position;
                adapter.notifyDataSetChanged();
                rlvDiretory.setVisibility(View.GONE);
                ivTitleArrow.setBackgroundResource(R.mipmap.icon_down_blacks);
            }
        });
        rlvDiretory.setOnClickListener(v -> {
            rlvDiretory.setVisibility(View.GONE);
            ivTitleArrow.setBackgroundResource(R.mipmap.icon_down_blacks);
        });
    }

    class DirectorysAdapter extends BaseQuickAdapter<Map<String, String>, BaseViewHolderEx> {
        private Context context;

        public DirectorysAdapter(int layoutResId, Context context, @io.reactivex.annotations.Nullable ArrayList<Map<String, String>> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, Map<String, String> entity) {
            TextView diretoryTv = helper.getView(R.id.diretory);
            diretoryTv.setText(entity.get("title"));
            if (index == helper.getItemPosition()) {
                diretoryTv.setSelected(true);
            } else {
                diretoryTv.setSelected(false);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
        }
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                int position = intent.getIntExtra("position", 0);
                int percent = intent.getIntExtra("percent", 0);
                boolean encryptStatus = intent.getBooleanExtra("encryptStatus", false);
                String recevierDataCode = intent.getStringExtra("dataCode");
                String fileUrl = intent.getStringExtra("fileUrl");
                String fileName = intent.getStringExtra("fileName");
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getDataCode().equals(recevierDataCode)) {
                        if (!list.get(i).isOpen()) {
                            if(encryptStatus){
                                list.get(i).setOpen(true);
                            }
                            dealData(position, percent, recevierDataCode, encryptStatus, fileUrl, fileName);
                        }

                    }
                }
            }
        }

    };

    /**
     * @param position
     * @param percent
     * @param recevierDataCode 处理广播数据
     * @param encryptStatus
     * @param fileUrl
     * @param fileName
     */
    private void dealData(int position, int percent, String recevierDataCode, boolean encryptStatus, String fileUrl, String fileName) {

        if (encryptStatus) {
            if (!MyApp.docunmentOpen) {
                Intent newIntent = new Intent(mContext, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                startActivity(newIntent);
            }
        } else {
            if (percent > 0 && percent < 100) {
                if (adapter != null) {
                    list.get(position).setProgress(percent);
                    adapter.notifyItemChanged(position);
                }
            } else if (percent == 100) {
                if (adapter != null) {
                    list.get(position).setProgress(100);
                    adapter.notifyItemChanged(position);
                    new Thread() {
                        @Override
                        public void run() {
                            AESEncrypt.encryptFile(mContext, fileUrl, fileName, recevierDataCode, "DocumentBaseSecondActivity_DownloadFile" + level);
                        }
                    }.start();
                }


            }else if (percent == 0) {
                //正常情况不会0
                Intent newIntent = new Intent(this, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                newIntent.putExtra("isError", true);
                startActivity(newIntent);
            }
        }
    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction("DocumentBaseSecondActivity_DownloadFile" + level);// 获取数据
        LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        HashMap<String, DownloadTask> map = MyApp.downloadTaskHashMap;
        for (String key : map.keySet()) {
            DownloadTask task = map.get(key);
            if (task != null) {
                task.cancel();
            }
        }
        if (mBroadcastReceiver != null && this != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
        }
        EventBus.getDefault().unregister(this);
    }


}
